<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="学生姓名" prop="studentName">
        <el-input
          v-model="queryParams.studentName"
          placeholder="请输入学生姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务名称" prop="taskName">
        <el-input
          v-model="queryParams.taskName"
          placeholder="请输入任务名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['edu:task:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['edu:task:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['edu:task:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['edu:task:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="taskList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="学生姓名" align="center" prop="studentName" />
      <el-table-column label="任务名称" align="center" prop="taskName" />
      <el-table-column label="开始时间" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="老师名称" align="center" prop="teacherName" />
      <el-table-column label="实际结束时间" align="center" prop="realEndTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.realEndTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="得分" align="center" prop="points" />
      <el-table-column label="准确率" align="center" prop="precision" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['edu:task:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['edu:task:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改学生任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" height="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="学生姓名" prop="studentName">
              <el-input v-model="form.studentName" placeholder="请输入学生姓名" >
                <el-button v-if="form.id == null" type="primary" slot="append" icon="el-icon-search"
                           @click="handleAddStudent"
                >选择
                </el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务名称" prop="taskName">
              <el-input v-model="form.taskName" placeholder="请输入任务名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker clearable v-model="form.startTime" style="width: 100%" type="date" value-format="yyyy-MM-dd" placeholder="请选择开始时间"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker clearable v-model="form.endTime" style="width: 100%" type="date" value-format="yyyy-MM-dd" placeholder="请选择结束时间"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
       <el-row>
         <el-col :span="24">
           <el-form-item label="备注" prop="remark">
             <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
           </el-form-item>
         </el-col>
       </el-row>
       <el-row>
         <el-col :span="24">

           <el-row :gutter="10" class="mb8">
             <el-col :span="1.5">
               <el-button type="primary" plain icon="el-icon-plus" size="mini"
                 @click="handleAddQuestion"
               >添加</el-button>
             </el-col>
             <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
           </el-row>

           <el-table :data="selectQuestionBankList" height="500px" >
             <el-table-column
               label="题干"
               align="center"
               prop="title"
               show-overflow-tooltip
             />
             <el-table-column label="学科" align="center" prop="subject">
               <template slot-scope="scope">
                 <dict-tag
                   :options="dict.type.edu_subject"
                   :value="scope.row.subject"
                 />
               </template>
             </el-table-column>
             <el-table-column label="题目类型" align="center" prop="questionType">
               <template slot-scope="scope">
                 <dict-tag
                   :options="dict.type.edu_question_type"
                   :value="scope.row.questionType"
                 />
               </template>
             </el-table-column>
             <el-table-column label="班级" align="center" prop="grades">
               <template slot-scope="scope">
                 <dict-tag :options="dict.type.edu_grades" :value="scope.row.grades"/>
               </template>
             </el-table-column>
             <el-table-column label="难易度" align="center" prop="level">
               <template slot-scope="scope">
                 <dict-tag
                   :options="dict.type.edu_facility_value"
                   :value="scope.row.grades"
                 />
               </template>
             </el-table-column>
             <el-table-column
               label="操作"
               align="center"
               class-name="small-padding fixed-width"
             >
               <template slot-scope="scope">
                 <el-button
                   size="mini"
                   type="text"
                   icon="el-icon-delete"
                   @click="handleDelete(scope.row)"
                   v-hasPermi="['edu:questionBank:remove']"
                 >删除
                 </el-button
                 >
               </template>
             </el-table-column>
           </el-table>


         </el-col>
       </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 选择学生 -->
    <el-dialog title="学生列表" :visible.sync="studentOpen" width="1000px" append-to-body>
      <el-form :model="studentQueryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
               label-width="80px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input
            v-model="studentQueryParams.name"
            placeholder="请输入姓名"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item label="联系人" prop="guardian">
          <el-input
            v-model="studentQueryParams.guardian"
            placeholder="请输入监护人"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="联系电话" prop="guardianPhone">
          <el-input
            v-model="studentQueryParams.guardianPhone"
            placeholder="请输入联系电话"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="studentHandleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="studentResetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table ref="studentTable" v-loading="studentLoading" :data="studentList" @select="handleStudentSelect"
                @select-all="handleStudentSelectAll"
      >
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="姓名" align="center" prop="name"/>
        <el-table-column label="性别" align="center" prop="gender">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.gender"/>
          </template>
        </el-table-column>
        <el-table-column label="联系人" align="center" prop="guardian"/>
        <el-table-column label="联系人电话" align="center" prop="guardianPhone"/>
        <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip/>
        <el-table-column label="所属机构名称" align="center" prop="tenantName"/>
      </el-table>

      <pagination
        v-show="studentTotal>0"
        :total="studentTotal"
        :page.sync="studentQueryParams.pageNum"
        :limit.sync="studentQueryParams.pageSize"
        @pagination="getStudentList"
      />

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitSelectForm">确 定</el-button>
        <el-button @click="cancelStudent">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 选择题库 -->
    <el-dialog title="题库列表" :visible.sync="questionOpen" width="1000px" append-to-body>

      <el-table ref="questionTable" v-loading="questionLoading" :data="questionBankList"
                @selection-change="handleQuestionSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column
          label="题干"
          align="center"
          prop="title"
          show-overflow-tooltip
        />
        <el-table-column label="学科" align="center" prop="subject">
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.edu_subject"
              :value="scope.row.subject"
            />
          </template>
        </el-table-column>
        <el-table-column label="题目类型" align="center" prop="questionType">
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.edu_question_type"
              :value="scope.row.questionType"
            />
          </template>
        </el-table-column>
        <el-table-column label="班级" align="center" prop="grades">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.edu_grades" :value="scope.row.grades"/>
          </template>
        </el-table-column>
        <el-table-column label="难易度" align="center" prop="level">
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.edu_facility_value"
              :value="scope.row.grades"
            />
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="questionTotal>0"
        :total="questionTotal"
        :page.sync="questionQueryParams.pageNum"
        :limit.sync="questionQueryParams.pageSize"
        @pagination="getQuestionList"
      />

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitQuestionSelectForm">确 定</el-button>
        <el-button @click="cancelQuestion">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTask, getTask, delTask, addTask, updateTask } from "@/api/edu/task";
import { listStudent } from '@/api/edu/student'
import { listQuestionBank } from '@/api/edu/questionBank'

export default {
  name: "Task",
  dicts: ['sys_user_sex',   'edu_question_type',
    'edu_grades',
    'edu_facility_value',
    'edu_subject'],
  data() {
    return {
      // 遮罩层
      loading: true,
      studentLoading:true,
      questionLoading:true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      studentTotal:0,
      questionTotal:0,
      // 学生任务表格数据
      taskList: [],
      // 学生数据
      studentList: [],
      questionBankList:[],
      selectQuestionBankList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      questionOpen:false,
      selectStudentOpen:false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        studentId: null,
        studentName: null,
        taskName: null,
        startTime: null,
        endTime: null,
        teacherId: null,
        teacherName: null,
        realEndTime: null,
        points: null,
        questionBankIds: null,
        trueQuestionIds: null,
        wrongQuestionIds: null,
        precision: null,
        tenantId: null,
        tenantName: null,
      },
      // 查询参数
      studentQueryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        birthday: null,
        gender: null,
        guardian: null,
        guardianPhone: null,
        startTime: null,
        endTime: null
      },
      // 查询参数
      questionQueryParams: {
        pageNum: 1,
        pageSize: 10
      },
      selectedStudentRow: null,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询学生任务列表 */
    getList() {
      this.loading = true;
      listTask(this.queryParams).then(response => {
        this.taskList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.selectQuestionBankList = [];
      this.form = {
        id: null,
        studentId: null,
        studentName: null,
        taskName: null,
        startTime: null,
        endTime: null,
        teacherId: null,
        teacherName: null,
        realEndTime: null,
        points: null,
        questionBankIds: null,
        trueQuestionIds: null,
        wrongQuestionIds: null,
        precision: null,
        remark: null,
        tenantId: null,
        tenantName: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAddStudent() {
      this.studentOpen = true
      this.getStudentList()
    },
    /** 查询学生列表 */
    getStudentList() {
      this.studentLoading = true
      listStudent(this.studentQueryParams).then(response => {
        this.studentList = response.rows
        this.studentTotal = response.total
        this.studentLoading = false
      })
    },
    studentHandleQuery() {
      this.studentQueryParams.pageNum = 1
      this.getStudentList()
    },
    studentResetQuery() {
      this.resetForm('studentQueryForm')
      this.studentHandleQuery()
    },
    handleStudentSelect(selection, row) {
      this.$refs.studentTable.clearSelection()
      if (selection.length > 0) {
        this.$refs.studentTable.toggleRowSelection(row, true)
        this.selectedStudentRow = row
      }
    },
    handleStudentSelectAll(selection) {
      if (selection.length > 0) {
        this.$refs.studentTable.clearSelection()
        this.selectedStudentRow = null
      }

    },
    cancelStudent() {
      this.studentOpen = false
      if (this.selectedStudentRow != null) {
        this.$refs.studentTable.clearSelection()
      }
    },
    submitSelectForm() {
      this.studentOpen = false
      this.form.studentId = this.selectedStudentRow.id
      this.form.studentName = this.selectedStudentRow.name
      this.selectedStudentRow = null
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加学生任务";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getTask(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改学生任务";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.questionBankIds = JSON.stringify(this.selectQuestionBankList.map(obj => obj.id));
          if (this.form.id != null) {
            updateTask(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTask(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除学生任务编号为"' + ids + '"的数据项？').then(function() {
        return delTask(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('edu/task/export', {
        ...this.queryParams
      }, `task_${new Date().getTime()}.xlsx`)
    },
    handleAddQuestion(){
      this.questionOpen = true
      this.getQuestionList()
    },
    getQuestionList(){
      this.questionLoading = true
      listQuestionBank(this.queryParams).then((response) => {
        this.questionBankList = response.rows
        this.questionTotal = response.total
        this.questionLoading = false
      })
    },
    cancelQuestion() {
      this.questionOpen = false
    },
    submitQuestionSelectForm() {
      this.questionOpen = false
    },
    // 多选框选中数据
    handleQuestionSelectionChange(selection) {
      let newSelectQuestionList = [...new Set([...this.selectQuestionBankList,...selection])];
      this.selectQuestionBankList = newSelectQuestionList;
    },
  }
};
</script>
